# -*- coding:utf-8 -*-
"""
作者:13505
日期:2021年03月18日
"""

import pymysql


# 连接数据库
def getConn():
    conn = pymysql.Connect(host="127.0.0.1", port=3306, user="test", password="123456", db="mydatabase",
                           charset="utf8", cursorclass=pymysql.cursors.DictCursor)
    return conn


# 插入数据
def insert(args):
    conn = getConn()
    cur = conn.cursor()
    sql = "insert into userinfo(user, password) values (%s, %s)"
    result = cur.execute(sql, args)
    print(result)
    if result > 0:
        print("插入成功！")
    else:
        print("插入数据失败！")
        conn.rollback()
        return False
    conn.commit()
    cur.close()
    conn.close()
    return True


# 更新数据
def update(args):
    conn = getConn()
    cur = conn.cursor()
    sql = "update userinfo set user=%s, password=%s where user=%s;"
    result = cur.execute(sql, args)
    print(result)
    if result > 0:
        print("成功更新数据！")
    else:
        conn.rollback()
        print("更新数据失败！")
        return False
    conn.commit()
    cur.close()
    conn.close()
    return True


# 查询数据
def query(args):
    conn = getConn()
    cur = conn.cursor()
    sql = "select * from userinfo where user=%s;"
    num = cur.execute(sql, args)
    result = cur.fetchall()
    conn.commit()
    cur.close()
    conn.close()
    if num > 0:
        print('查询成功！')
    else:
        print("查询失败！")
        return False
    result = list(result)
    return result


# 删除数据
def delete(args):
    conn = getConn()
    cur = conn.cursor()
    sql = "delete from userinfo where user=%s;"
    result = cur.execute(sql, args)
    print(result)
    if result > 0:
        print("删除成功！")
    else:
        conn.rollback()
        print("删除失败！")
        return False
    conn.commit()
    cur.close()
    conn.close()
    return True

# 通用操作
def change(sql, args):
    conn = getConn()
    cur = conn.cursor()
    result = cur.execute(sql, args)
    print(result)
    if result > 0:
        print("数据库操作成功！")
    else:
        print("数据库操作失败！")
        conn.rollback()
        return False
    conn.commit()
    cur.close()
    conn.close()
    return result


if __name__ == '__main__':
    agrs = ('111',)
    query(agrs)
